﻿using Lg.Core.Exceptions;
using Microsoft.AspNetCore.Http;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;

namespace Lg.Core.ImageHelper
{
    public class Base
    {

        /// <summary>
        /// 根据base64字符串返回一个封装好的GDI+位图。
        /// </summary>
        /// <param name="base64string">可转换成位图的base64字符串。</param>
        /// <returns>Bitmap对象。</returns>
        public Bitmap GetImageFromBase64(string base64string)
        {
            byte[] b = Convert.FromBase64String(base64string);
            using (MemoryStream ms = new MemoryStream(b))
            {
                Bitmap bitmap = new Bitmap(ms);
               
                return bitmap;
            }
        }

        private string GetImageExt(Guid guid)
        {
            if (guid == System.Drawing.Imaging.ImageFormat.Gif.Guid)
            {
                return "gif";
            }
            else if (guid == System.Drawing.Imaging.ImageFormat.Png.Guid)
            {
                return "png";
            }
            else if (guid == System.Drawing.Imaging.ImageFormat.Jpeg.Guid)
            {
                return "jpg";
            }
            else if (guid == System.Drawing.Imaging.ImageFormat.Bmp.Guid)
            {
                return "bmp";
            }
            else
            {
                return null;
            }
        }
        /// <summary>
        /// 通过扩展名判断是否为图片类型
        /// </summary>
        /// <param name="extName"></param>
        /// <returns></returns>

        public static bool IsImage(string extName)
        {
            List<string> ImageExtNameList = new List<string>
            {
               "bmp","emf","exif","gif","icon","jpeg","jpg","memorybmp","png","tiff","wmf"
            };
            extName=extName.ToLower().Replace(".","");
            return ImageExtNameList.Contains(extName);
        }

        public Image Compress(byte[] bytes)
        {
            Stream stream=new MemoryStream(bytes);
            Image oldImg = Image.FromStream(stream);
            int outW = 900; int outH = 900;
            if (oldImg.Width > 1000)
            {
                outH = 900 * oldImg.Height / oldImg.Width;
                Image newimg = new Bitmap(outW, outH);
                using (Graphics g = Graphics.FromImage(newimg))
                {
                    g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                    g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                    g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
                    g.DrawImage(oldImg, new Rectangle(0, 0, outW, outH), new Rectangle(0, 0, oldImg.Width, oldImg.Height), GraphicsUnit.Pixel);
                    g.Dispose();
                }

                return newimg;
            }
            else
            {
                return oldImg;
            }
        }

        /// <summary>
        /// 压缩图片并返回IFormFile对像
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public async Task<FormFile> CompressImage(IFormFile file)
        {
            using var stream=new MemoryStream();
            file.OpenReadStream().CopyTo(stream);
            byte[] bytes= await CompressImage(stream.ToArray());
            FormFile formFile = new FormFile(new MemoryStream(bytes), 0, bytes.Length, file.Name, file.FileName);
            return formFile;
        }

        public async Task<byte[]> CompressImage(byte[] bytes)
        {
            return await Task.Run(() =>
            {
                try
                {
                    using (var originalImage = Image.FromStream(new MemoryStream(bytes)))
                    {
                        ImageFormat format = originalImage.RawFormat;
                        // 保持原始宽高比，计算压缩后的尺寸（若需要）
                        var newSize = CalculateResizedDimensions(originalImage.Size, maxWidth: 1920, maxHeight: 1080);
                        using (var resizedImage = new Bitmap(newSize.Width, newSize.Height))
                        {
                            using var graphics = Graphics.FromImage(resizedImage);
                            graphics.CompositingQuality = CompositingQuality.HighSpeed;
                            graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                            graphics.SmoothingMode = SmoothingMode.HighSpeed;
                            graphics.DrawImage(originalImage, 0, 0, newSize.Width, newSize.Height);
                            using var saveStream = new MemoryStream();
                            resizedImage.Save(saveStream, format);
                            return saveStream.ToArray();
                        }
                    }
                }
                catch (Exception e)
                {
                    throw new LgException("不是有效的图片格式");
                }

            });
            // 加载图片
            
        }
        private static ImageCodecInfo GetEncoderInfo(string mimeType)
        {
            foreach (ImageCodecInfo codec in ImageCodecInfo.GetImageEncoders())
            {
                if (codec.MimeType == mimeType)
                {
                    return codec;
                }
            }
            throw new ArgumentException($"No codec for MIME type '{mimeType}' found.");
        }
        private Size CalculateResizedDimensions(Size originalSize, int maxWidth, int maxHeight)
        {
            float ratioX = (float)maxWidth / originalSize.Width;
            float ratioY = (float)maxHeight / originalSize.Height;
            float ratio = Math.Min(ratioX, ratioY);
            return new Size((int)(originalSize.Width * ratio), (int)(originalSize.Height * ratio));
        }
    }
}
